package service.impl;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import dao.UserDAO;
import entity.User;
import service.UserService;
import util.Constant;
import util.ImageUtil;
import util.MD5;
import util.UUID;

public class UserServiceImpl implements UserService{
	//使用spring容器注入
	private UserDAO userDao;
	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}
	public boolean checkEmail(String email) throws Exception{
		User user =userDao.findByEmail(email);
		if(user!=null){
			return true;
		}else {
			return false;
		}
	}
	public boolean checkEmailCode(User user,String code,Map<String, Object> session) throws Exception{
		user=userDao.findByEmailVerifyCode(code);
		if(user==null){
			return false;
		}else{
			session.put("user", user);
			user.setIsEmailVerify("Y");
			userDao.modify(user);
//			userDao.UpdateEmailVerifyCode(code);
			return true;
		}
	}
	public String checkLogin(String name,String password,Map<String, Object> session,HttpServletRequest httpReq) throws Exception{
		User user = userDao.findByEmail(name);
		if(user!=null && user.getPassword().equals(MD5.md5(password))){
			//判断是否验证已激活
			if(user.getIsEmailVerify().equals("N")){
				return "verify";
			}else{
				user.setLastLoginIp(httpReq.getRemoteAddr());
				user.setLastLoginTime(System.currentTimeMillis());
				userDao.modify(user);
				session.put("user", user);
				System.out.println(session.get("user"));
				return "success";
			}
		}else{
			return "error";
		}
	}
	public boolean checkNumber(String number,Map<String,Object> session){
		String code = (String) session.get("code");
		System.out.println(code);
		if(number.equalsIgnoreCase(code)){
			return true;
		}else {
			return false;
		}
	}
	public void register(User user,HttpServletRequest httpReq) throws Exception{
		//完善用户数据
		user.setUserIntegral(Constant.NORMAL);
		user.setIsEmailVerify(Constant.NO);
		user.setEmailVerifyCode(UUID.uuid());
		user.setLastLoginIp(httpReq.getRemoteAddr());
		user.setLastLoginTime(System.currentTimeMillis());
		//加密密码
		user.setPassword(MD5.md5(user.getPassword()));
		//保存数据
		userDao.save(user);
	}
	public void SessionOut(Map<String,Object> session){
		session.remove("user");
		session.clear();
	}
	public InputStream checkCode(Map<String,Object> session)throws Exception{
		Map<String,BufferedImage> map = ImageUtil.createImage();
		String code = map.keySet().iterator().next();
		session.put("code", code);
		return ImageUtil.getInputStream(map.get(code));
	}
}
